package com.it.demo.filter;

import com.it.demo.entity.SecurityUser;
import com.it.demo.entity.User;
import com.it.demo.entity.common.Result;
import com.it.demo.util.JWTUtil;
import com.it.demo.util.WebUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    JWTUtil jwtUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException, ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            //token为空的话, 就不管它, 让SpringSecurity中的其他过滤器处理请求
            //请求放行
            filterChain.doFilter(request, response);
            return;
        }
        //token不为空时, 解析token
        User user = null;
        try {
            user = jwtUtil.verify(token);
        } catch (Exception e) {
            // 过滤器中抛出的异常，无法被统一异常捕获，所以在这里直接返回
            e.printStackTrace();
            Result result = new Result();
            result.setCode(403);
            result.setMsg("Token无效：" + e.getMessage());
            WebUtils.response(response,result);
            return;
        }
        SecurityUser securityUser = new SecurityUser();
        securityUser.setUser(user);
        //将用户安全信息存入SecurityContextHolder, 在之后SpringSecurity的过滤器就不会拦截
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(securityUser, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);
    }
}
